package com.walker.kuyun.viewmodel

import android.util.Log
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.walker.kuyun.App
import com.walker.kuyun.R
import com.walker.kuyun.bean.TabBean
import com.walker.kuyun.config.Api
import com.walker.kuyun.ui.adapter.SerializableRecycledViewPool
import com.walker.kuyun.util.JsoupUtil
import com.walker.kuyun.util.Util.showToastOnThread
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.jsoup.select.Elements
import java.util.*


class HomeViewModel : ViewModel() {
    val childViewPool = SerializableRecycledViewPool()
    val viewPool = SerializableRecycledViewPool()
    var allTabList: MutableList<TabBean> = ArrayList()
    var mldGetAllTabList: MutableLiveData<Boolean> = MutableLiveData()
    val hintList = arrayListOf<String>()

    fun getAllTabData() {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val document = JsoupUtil.getDocument(Api.MAIN_URL)

                allTabList.clear()
                hintList.clear()
                //hot search
                val hintSelector = document.select(".fed-pops-hot span.fed-name")
                for (element in hintSelector) {
                    hintList.add(element.text())
                }

                val menu: Elements = document.getElementsByClass("fed-part-eone")

                for (i in menu.indices) {
                    val url = menu[i].attr("href")
                    if (url.startsWith("/vod/type"))
                        allTabList.add(TabBean("", url, Api.MAIN_URL + url, menu[i].text()))
                }

                mldGetAllTabList.postValue(true)
            } catch (e: Exception) {
                allTabList.clear()
                mldGetAllTabList.postValue(false)
                e.printStackTrace()
                (App.getApp()
                    .getString(R.string.get_data_failed) + "\n" + e.message).showToastOnThread(
                    Toast.LENGTH_LONG
                )
            }
        }
    }

    companion object {
        const val TAG = "HomeViewModel"
    }
}